package com.ad.platform.common.interceptor;

import com.ad.payload.exception.ErrorMapping;
import com.ad.payload.exception.ExceptionEntity;
import com.ad.payload.model.CurrentUser;
import com.ad.payload.util.JwtUtil;
import com.ad.platform.common.config.IgnoreUrlsConfig;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author:dxgong
 * @日期 2021/3/26 10:02
 * @注释 拦截器 处理用户登录信息
 */
@Component
@Slf4j
public class WebInterceptorAdapter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    /**
     * 处理前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authentication = request.getHeader(HttpHeaders.AUTHORIZATION);

        String requestURI = request.getRequestURI();

        /*if(request.getRequestURI().endsWith("/needCheck") || request.getRequestURI().endsWith("/hasPermission")){
            return true;
        }*/
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单接口不做拦截
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        if(ignoreUrls!=null){
            for (String ignoreUrl : ignoreUrls) {
                if (pathMatcher.match(ignoreUrl, request.getRequestURI())) {
                    return true;
                }
            }
        }

        Claims claims = null;
        String userName = null;
        String id = null;
        String uuid = null;
        try {
            claims = jwtUtil.parseJWT(authentication);
            if(claims != null){
                userName = String.valueOf(claims.get("weChatName"));
                id = String.valueOf(claims.get("id").toString());
                uuid = String.valueOf(claims.get("uuid"));
            }
        } catch (Exception e){
            response.setStatus(478);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            PrintWriter output = response.getWriter();
            ExceptionEntity entity = new ExceptionEntity();
            entity.setExceptionType(SystemException.class.getName());
            entity.setErrCode(ErrorMapping.ACCESS_TOKEN_INVALID);
            entity.setReferenceCode(ErrorMapping.getReferenceCode());
            entity.setMessage(ErrorMapping.MESSAGE_MAP.get(ErrorMapping.ACCESS_TOKEN_INVALID));
            output.println(JSON.toJSONString(entity));
            output.flush();
            output.close();
            return false;
        }

        CurrentUser currentUser = null;

        currentUser = new CurrentUser();
        currentUser.setId(id);
        currentUser.setWeChatName(userName);
        currentUser.setUuid(uuid);
        RequestHolder.setCurrentUser(currentUser);

        RequestHolder.add(request);
        log.info("GlobalInterceptor RequestHolder CurrentUser:"+JSON.toJSONString(currentUser));
        return true;
    }
}
